package com.example.chatroom.controller;

import com.example.chatroom.common.errorcode.ControllerErrorCodeConstants;
import com.example.chatroom.common.exception.ControllerException;
import com.example.chatroom.common.pojo.CommonResult;
import com.example.chatroom.controller.param.GetMessagesParam;
import com.example.chatroom.controller.result.GetMessagesResult;
import com.example.chatroom.service.IMessageService;
import com.example.chatroom.service.dto.GetMessagesDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private IMessageService messageService;
    @RequestMapping("/getMessages")
    public CommonResult<List<GetMessagesResult>> getMessages( @Validated GetMessagesParam getMessagesParam){
      log.info("getMessages getMessagesParam:{}",getMessagesParam);
        List<GetMessagesDTO> messagesDTOS=messageService.getMessages(getMessagesParam);
      return CommonResult.success(convertToGetMessagesResult(messagesDTOS));
    }

    private List<GetMessagesResult> convertToGetMessagesResult(List<GetMessagesDTO> messagesDTOS) {
        if(messagesDTOS.isEmpty()){
            log.error(ControllerErrorCodeConstants.MESSAGE_GET_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.MESSAGE_GET_ERROR);
        }
        return messagesDTOS.stream().map(messagesDTO->{
            GetMessagesResult getMessagesResult=new GetMessagesResult();
            getMessagesResult.setMessageId(messagesDTO.getId());
            getMessagesResult.setFromId(messagesDTO.getFormId());
            getMessagesResult.setFromName(messagesDTO.getFromName());
            getMessagesResult.setSessionId(messagesDTO.getSessionId());
            getMessagesResult.setContent(messagesDTO.getContent());
            getMessagesResult.setPostTime(messagesDTO.getGmtCreate());
            return getMessagesResult;
        }).collect(Collectors.toList());

    }
}
